package com.anjiplus.gaea.oss.file;

import com.anji.plus.gaea.oss.ossbuilder.GaeaOSSTemplate;
import com.anji.plus.gaea.oss.utils.ResponseUtil;
import com.anji.plus.gaea.oss.utils.StringPatternUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.CacheControl;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;

@Service
public class FileServiceImpl implements FileService{

    private static Logger logger = LoggerFactory.getLogger(FileServiceImpl.class);

    @Autowired
    private GaeaOSSTemplate gaeaOSSTemplate;

    @Override
    public String upload(MultipartFile file) {
        String fileName = gaeaOSSTemplate.uploadFileByInputStream(file);
        return fileName;
    }

    @Override
    public ResponseEntity<byte[]> download(HttpServletRequest request, HttpServletResponse response, String fileName) {
        try{
            String userAgent = request.getHeader("User-Agent");
            boolean isIEBrowser = userAgent.indexOf("MSIE") > 0;
            String fileSuffix = fileName.substring(fileName.lastIndexOf("."));

            // 调用文件存储工厂，读取文件，返回字节数组
            byte[] fileBytes = gaeaOSSTemplate.downloadFile(fileName);

            //根据文件后缀来判断，是显示图片\视频\音频，还是下载文件
            ResponseEntity<byte[]> responseEntity = ResponseUtil.writeBody(fileName, fileBytes, isIEBrowser);
            return responseEntity;
        } catch (Exception e) {
            logger.error("file download error: {}", e);
            return null;
        }
    }
}
